#include "crc.h"

crc::crc() {}

uint16_t crc::crc16(const uint8_t* buf, uint16_t size)
{
    uint16_t crc = 0xFFFF; // 初始化CRC寄存器
    uint16_t polynomial = 0xA001; // CRC-16多项式

    while (size--)
    {
        crc ^= *buf++; // 将当前字节与CRC寄存器异或
        for (int i = 0; i < 8; i++)
        {
            if (crc & 1)
            {
                crc = (crc >> 1) ^ polynomial; // 如果最低位是1，右移并与多项式异或
            }
            else
            {
                crc >>= 1; // 否则直接右移
            }
        }
    }

    return crc;
}

uint32_t crc::crc32(const uint8_t *buf, uint32_t size)
{
    uint32_t crc = 0xFFFFFFFF;
    uint32_t polynomial = 0xEDB88320;

    while (size--) {
        crc ^= *buf++;
        for (int i = 0; i < 8; i++) {
            if (crc & 1)
                crc = (crc >> 1) ^ polynomial;
            else
                crc >>= 1;
        }
    }

    return crc ^ 0xFFFFFFFF;
}
